﻿using System.Text.Json;
using System.Text.Json.Serialization;

namespace BPM.Web.Shared.Converters
{
    public class DateTimeNullHandlingConverter : JsonConverter<DateTime?>
    {
        public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String && DateTime.TryParse(reader.GetString(), out var result))
            {
                return result;
            }

            return null;
        }

        public override void Write(Utf8JsonWriter writer, DateTime? dateTimeValue, JsonSerializerOptions options)
        {
            if (dateTimeValue.HasValue)
                writer.WriteStringValue(dateTimeValue.Value);
            else
                writer.WriteNullValue();
        }
    }
}
